<template>
  <PageWrapper dense contentFullHeight fixed-height contentClass="flex">
    <div class="w-1/6 xl:w-1/6 mr-2 overflow-hidden bg-white">
      <BasicTree
        :title="t('表单分类')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </div>
    <div class="w-5/6 xl:w-5/6">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <div class="toolbar-defined">
            <a-button type="primary" @click="handleCreate" v-auth="'form-design:add'">
              <template #icon><PlusOutlined /></template>
              {{ t('新增') }}
            </a-button>
            <a-button @click="handleDelete" v-auth="'form-design:batchDelete'">{{
              t('批量删除')
            }}</a-button>
            <a-button @click="previewForm" v-auth="'form-design:previewForm'">{{
              t('预览表单')
            }}</a-button>
            <!-- <a-button @click="queryHistory">{{ t('历史记录') }}</a-button> -->
            <a-button @click="handleCategory" v-auth="'form-design:classifyMGT'">{{
              t('分类管理')
            }}</a-button>
            <a-button @click="handleCodeGenerator" v-auth="'form-design:generatedCode'">{{
              t('生成代码')
            }}</a-button>
          </div>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                auth: 'form-design:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                auth: 'form-design:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>

    <DesignModal @register="registerDesignModal" @success="reload" />
    <!-- <HistoryModal @register="registerHistoryModal" /> -->
    <CategoryModal title="表单" :dicId="dicId" @register="registerCategoryModal" @success="fetch" />
    <PreviewModal @register="registerPreviewModal" />
    <DataFirstModal
      v-if="state.isShowDataFirst"
      @register="registerDataFirst"
      @success="handleSuccess"
      @close="handleClose('isShowDataFirst')"
    />
    <CodeFirstModal
      v-if="state.isShowCodeFirst"
      @register="registerCodeFirst"
      @success="handleSuccess"
      @close="handleClose('isShowCodeFirst')"
    />
    <SimpleTemplateModal
      v-if="state.isShowSimpleTemplate"
      @register="registerSimpleTemplate"
      @success="handleSuccess"
      @close="handleClose('isShowSimpleTemplate')"
    />
    <CodeGeneratorModal
      v-if="state.isShowCodeGenerator"
      @register="registerCodeGenerator"
      @close="handleClose('isShowCodeGenerator')"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getFormTemplatePage,
    deleteFormTemplate,
    updateFormTemplateStatus,
    getFormTemplate,
  } from '/@/api/form/design';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import DesignModal from './components/DesignModal.vue';
  // import HistoryModal from './components/HistoryModal.vue';
  import { CategoryModal } from '/@/components/CategoryModal';
  import PreviewModal from './components/PreviewModal.vue';
  import DataFirstModal from './components/components/DataFirstModal.vue';
  import CodeFirstModal from './components/components/CodeFirstModal.vue';
  import SimpleTemplateModal from './components/components/SimpleTemplateModal.vue';
  import CodeGeneratorModal from './components/CodeGeneratorModal.vue';
  import { h, onMounted, ref, createVNode, reactive, computed } from 'vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDicDetailList } from '/@/api/system/dic';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import { Switch, Modal } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const treeData = ref<TreeItem[]>([]);
  const selectId = ref('');
  const selectedKeys = ref<string[]>([]);
  const dicId = '1419276800524424444';

  const state = reactive({
    isShowDataFirst: true,
    isShowCodeFirst: true,
    isShowSimpleTemplate: true,
    isShowCodeGenerator: true,
  });
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      dataIndex: 'name',
      title: t('名称'),
      align: 'left',
    },

    {
      dataIndex: 'categoryName',
      title: t('分类'),
      align: 'left',
    },

    {
      dataIndex: 'enabledMark',
      title: t('状态'),
      width: 120,
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          onChange(checked: boolean) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 0;
            const { createMessage } = useMessage();
            updateFormTemplateStatus(record.id, newStatus)
              .then(() => {
                record.enabledMark = newStatus;
                createMessage.success(t('已成功修改状态'));
              })
              .catch(() => {
                createMessage.error(t('修改状态失败'));
              })
              .finally(() => {
                record.pendingStatus = false;
              });
          },
        });
      },
    },
    {
      dataIndex: 'createUserName',
      title: t('创建人'),
      align: 'left',
    },
    {
      dataIndex: 'createDate',
      title: t('创建时间'),
      align: 'left',
    },
    {
      dataIndex: 'remark',
      align: 'left',
      title: t('备注'),
    },
  ];
  const { notification } = useMessage();

  const [registerDesignModal, { openModal: openDesignModal }] = useModal();
  // const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerPreviewModal, { openModal: openPreviewModal }] = useModal();
  const [registerDataFirst, { openModal: openDataFirstModal }] = useModal();
  const [registerCodeFirst, { openModal: openCodeFirstModal }] = useModal();
  const [registerSimpleTemplate, { openModal: openSimpleTemplateModal }] = useModal();
  const [registerCodeGenerator, { openModal: openCodeGeneratorModal }] = useModal();

  const [registerTable, { reload, setSelectedRowKeys }] = useTable({
    api: getFormTemplatePage,
    rowKey: 'id',
    title: '表单列表',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [],
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选id
      return { ...params, category: selectId.value, type: FormTypeEnum.CUSTOM_FORM };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      onChange: onSelectChange,
    },
    customRow,
  });

  const formId = computed(() => {
    return selectedKeys.value && selectedKeys.value.length
      ? selectedKeys.value[selectedKeys.value.length - 1]
      : '';
  });

  function onSelectChange(rowKeys: string[]) {
    selectedKeys.value = rowKeys;
    setSelectedRowKeys(selectedKeys.value);
  }

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  }

  function handleCreate() {
    openDesignModal(true, {
      title: t('添加表单'),
    });
  }

  function handleEdit(record: Recordable) {
    switch (record.formDesignType) {
      case 0:
        openDataFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case 1:
        openCodeFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case 2:
        openSimpleTemplateModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
    }
  }

  function handleDelete(record: Recordable = {}) {
    const ids = record.id ? [record.id] : selectedKeys.value;
    if (!ids.length) {
      noticeInfo(t('删除'));
      return;
    }
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('确定要删除所选项吗？'),
      onOk() {
        deleteFormTemplate(ids).then(() => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          });
        });
      },
      onCancel() {},
      okText: t('确认'),
      cancelText: t('取消'),
    });
  }

  function handleCodeGenerator() {
    if (!formId.value) {
      noticeInfo(t('生成'));
      return;
    }
    openCodeGeneratorModal(true, { formId: formId.value });
  }

  function handleSuccess() {
    reload();
  }

  function handleClose(modal) {
    state[modal] = !state[modal];
    setTimeout(() => {
      state[modal] = !state[modal];
    }, 100);
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({ searchInfo: { category: selectIds[0] } });
  }

  function handleCategory() {
    openCategoryModal(true, { title: t('表单分类管理') });
  }

  async function fetch() {
    treeData.value = (await getDicDetailList({
      itemId: dicId,
    })) as unknown as TreeItem[];
  }

  async function previewForm() {
    if (!formId.value) {
      noticeInfo(t('预览'));
      return;
    }
    const templateJson = await getFormTemplate(formId.value);
    openPreviewModal(true, { title: t('预览'), formJson: templateJson.formJson });
  }

  // async function queryHistory() {
  //   if (!formId.value) {
  //     noticeInfo(t('查询'));
  //     return;
  //   }
  //   openHistoryModal(true, { title: t('历史记录'), formId: formId.value });
  // }

  function noticeInfo(info: string) {
    notification.warning({
      message: t('提示'),
      description: t(`请先选择要{notice}的数据项`, { notice: info }),
    }); //提示消息
  }

  onMounted(() => {
    fetch();
  });
</script>
<style lang="less" scoped>
  .toolbar-defined {
    :deep(.ant-btn) {
      margin-left: 5px;
    }
  }
</style>
